package com.idroc.lab.testing;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

import com.idroc.coelacanth.core.membership.HeartBeatBroadcastMessage;
import com.idroc.coelacanth.core.message.Message;
import com.idroc.coelacanth.core.message.MessageDispatchHandler;
import com.idroc.coelacanth.core.message.MessageFactory;

public class MessageTestServer {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		ChannelFactory factory =
			new NioServerSocketChannelFactory (
			Executors.newCachedThreadPool(),
			Executors.newCachedThreadPool());
			ServerBootstrap bootstrap = new ServerBootstrap (factory);
			
			MessageFactory fac = new MessageFactory();
			
			MessageDispatchHandler dispatcher = fac.getMessageDispatcher();
			dispatcher.addUpMessageHandler(TestMessage.class, new MessageHandler());
			dispatcher.addDownMessageHandler(TestMessage.class, new MessageHandler());
			
			dispatcher.addUpMessageHandler(HeartBeatBroadcastMessage.class, new MessageHandler()); 
			
			bootstrap.setPipelineFactory(fac);
			bootstrap.setOption("child.tcpNoDelay", true);
			bootstrap.setOption("child.keepAlive", true);
			bootstrap.bind(new InetSocketAddress(9090));
	} 
	
	@ChannelPipelineCoverage("all")
	static class MessageHandler extends SimpleChannelHandler {

		@Override
		public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
				throws Exception { 
			Message msg = (Message) e.getMessage();
			System.out.println("msg->" + msg);
			TestMessage tm = new TestMessage();
			tm.setMsg("server send echo message:test message");			
			Channels.write(ctx, e.getFuture(), tm, e.getRemoteAddress());
		}
		
	}
}
